<?php

namespace app\system\service;

use app\model\Stock;
use app\model\StockSettingTpl;
use app\traits\ServiceTrait;
use app\traits\UserTrait;
use think\helper\Arr;

class StockSettingTplService
{
    use UserTrait;
    use ServiceTrait;

    public function getList(?array $params, $select = ['*'], $sample = false)
    {
        $query = StockSettingTpl::order(['id' => 'desc']);
        if ($name = Arr::get($params, 'name')) {
            $query->where(['name' => $name]);
        }
        $pagination = $query
            ->field($select)
            ->paginate([
                'list_rows' => Arr::get($params, $this->listRowsName('system'), 15),
                'var_page' => 'page',
            ]);
        return $sample ? $pagination->items() : pagination($pagination);
    }
    
    /**
     * @param $id
     * @return array
     */
    public function read($id): array
    {
        return [true, StockSettingTpl::where(['StockSettingTpl_id' => $id])->findOrEmpty()->toArray()];
    }


    public function save(array $params, $adminId = 0): array
    {
        if (!Arr::get($params, 'name')) {
            return [false, '缺少必要参数name'];
        }
        $model = new StockSettingTpl();
        $params['created_by'] = $this->getUid($adminId);
        $model->save($params);
        return [true, $model];
    }

    public function update($id, array $data): array
    {
        $model = StockSettingTpl::where('id', $id)->find();
        $data = array_merge($data, [
            'updated_by' => $this->getUid(),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        return [true, $model->save($data)];
    }

    /**
     * 删除
     * @param $id
     * @param $adminId
     * @return array
     */
    public function del($id, $adminId = 0)
    {
        $model = StockSettingTpl::update([
            'deleted_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => $this->getUid($adminId),
        ], ['id' => $id]);
        return [true, $model];
    }

}